package com.xiaoxin.experience.api.environment;

import com.xiaoxin.experience.api.environment.model.EnvironmentInfo;
import com.xiaoxin.experience.common.RestResponse;
import com.xiaoxin.experience.service.environment.EnvironmentService;
import com.xiaoxin.experience.util.DateUtil;
import com.xiaoxin.experience.util.FileUtil;
import com.xiaoxin.experience.util.ServletUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.file.attribute.FileTime;
import java.util.Date;
import java.util.Enumeration;
import java.util.Objects;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author xiaoxin
 */
@RestController
@RequestMapping("/api/env")
public class EnvController
{

    @Resource
    private EnvironmentService environmentService;

    @GetMapping("/config")
    public RestResponse<EnvironmentInfo> getConfig(HttpServletRequest request)
    {
        return RestResponse.success(environmentService.getConfig(ServletUtil.getRequestIPAddress(request)));
    }

    @PutMapping("/config")
    public RestResponse<Boolean> setConfig(@RequestBody EnvironmentInfo environmentInfo,HttpServletRequest request)
    {
        if (Objects.nonNull(environmentInfo))
        {
            environmentInfo.setRemoteIp(ServletUtil.getRequestIPAddress(request));
        }
        environmentService.setConfig(environmentInfo);
        return RestResponse.success();
    }

    @GetMapping("/version")
    public RestResponse<String> getVersion()
    {
        String jarPath = System.getProperty("java.class.path");
        try(JarFile jarFile = new JarFile(jarPath))
        {
            String name = jarFile.getName();
            String app = FileUtil.trimFileExt(name);
            Enumeration<JarEntry> entries = jarFile.entries();
            if (entries.hasMoreElements())
            {
                JarEntry jarEntry = entries.nextElement();
                FileTime lastModifiedTime = jarEntry.getLastModifiedTime();
                String buildTime = DateUtil.formatTime(new Date(lastModifiedTime.toMillis()), DateUtil.YMDHMS);
                return RestResponse.success(app + " " + this.getClass().getPackage().getImplementationVersion() + "-" + buildTime);
            }
        }
        catch (Exception e)
        {
            // ignore
        }
        return RestResponse.fail();
    }
}
